<template>
    <v-container>
      <v-row justify="center">
        <v-col cols="12" md="6">
          <v-card class="pa-6">
            <v-card-title class="text-h5 text-center mb-4">
              账户充值
            </v-card-title>
            
            <v-card-text>
              <v-form @submit.prevent="handleRecharge">
                <v-text-field
                  v-model="amount"
                  label="充值金额"
                  type="number"
                  :rules="amountRules"
                  prefix="¥"
                  min="0.01"
                  step="0.01"
                  required
                  outlined
                ></v-text-field>
                
                <v-alert
                  v-if="error"
                  type="error"
                  class="mb-4"
                >
                  {{ error }}
                </v-alert>
                
                <v-row>
                  <v-col cols="8">
                    <v-btn
                      type="submit"
                      color="primary"
                      block
                      size="large"
                      :loading="loading"
                      :disabled="!isValidAmount"
                    >
                      立即充值
                    </v-btn>
                  </v-col>
                  <v-col cols="4">
                    <v-btn
                      color="warning"
                      block
                      size="large"
                      @click="clearPendingCharge"
                      :loading="clearLoading"
                    >
                      清除订单
                    </v-btn>
                  </v-col>
                </v-row>
              </v-form>
            </v-card-text>
          </v-card>
          
          <!-- 充值历史 -->
          <v-card class="mt-6">
            <v-card-title class="text-h6">
              充值记录
            </v-card-title>
            <v-card-text>
              <v-data-table
                :headers="historyHeaders"
                :items="rechargeHistory"
                :loading="historyLoading"
                class="elevation-1"
              >
                <template v-slot:item.amount="{ item }">
                  ¥{{ item.amount }}
                </template>
                <template v-slot:item.rechargeTime="{ item }">
                  {{ formatDate(item.rechargeTime) }}
                </template>
              </v-data-table>
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>
    </v-container>
  </template>
  
  <script>
  import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../services/api.js'
  
  export default {
    name: 'RechargePage',
    setup() {
      const router = useRouter()
      const amount = ref('')
      const loading = ref(false)
      const clearLoading = ref(false)
      const error = ref('')
      const rechargeHistory = ref([])
      const historyLoading = ref(false)
  
      const amountRules = [
        v => !!v || '请输入充值金额',
        v => parseFloat(v) > 0 || '充值金额必须大于0',
        v => parseFloat(v) <= 10000 || '单次充值金额不能超过10000元'
      ]
  
      const historyHeaders = [
        { title: '充值金额', key: 'amount', align: 'center' },
        { title: '充值时间', key: 'rechargeTime', align: 'center' }
      ]
  
      const isValidAmount = computed(() => {
        const num = parseFloat(amount.value)
        return num > 0 && num <= 10000
      })
  
      const handleRecharge = async () => {
        if (!isValidAmount.value) {
          error.value = '请输入有效的充值金额'
          return
        }
  
        loading.value = true
        error.value = ''
  
              try {
        // 调用支付宝支付接口
        const response = await api.alipayPay(parseFloat(amount.value))

        if (response.status === 200) {
          // 获取支付宝支付页面HTML
          const html = response.data
          
          // 创建新标签页显示支付宝支付页面
          const newTab = window.open('', '_blank')
          newTab.document.write(html)
          newTab.document.close()
          
          // 清空输入框
          amount.value = ''
          
          // 刷新充值历史
          loadRechargeHistory()
        } else {
          error.value = '充值失败，请重试'
        }
      } catch (err) {
        console.error('充值失败:', err)
        if (err.response && err.response.data) {
          const errorMessage = err.response.data.message || '充值失败，请重试'
          error.value = errorMessage
          
          // 如果是未完成订单错误，提示用户清除订单
          if (errorMessage.includes('未完成的充值订单')) {
            error.value = '存在未完成的充值订单，请点击"清除订单"按钮后再试'
          }
        } else {
          error.value = '网络错误，请检查网络连接后重试'
        }
      } finally {
        loading.value = false
      }
      }
  
                const loadRechargeHistory = async () => {
        historyLoading.value = true
        try {
          const response = await api.getAlipayHistory()
          if (response.status === 200) {
            rechargeHistory.value = response.data
          } else {
            console.error('获取充值历史失败')
          }
        } catch (err) {
          console.error('获取充值历史失败:', err)
        } finally {
          historyLoading.value = false
        }
      }

      const clearPendingCharge = async () => {
        clearLoading.value = true
        error.value = ''
        try {
          await api.alipayCancel()
          error.value = '已清除未完成的充值订单'
          setTimeout(() => {
            error.value = ''
          }, 3000)
        } catch (err) {
          console.error('清除订单失败:', err)
          error.value = '清除订单失败，请重试'
        } finally {
          clearLoading.value = false
        }
      }
  
      const formatDate = (dateString) => {
        if (!dateString) return ''
        const date = new Date(dateString)
        return date.toLocaleString('zh-CN')
      }
  
      onMounted(() => {
        loadRechargeHistory()
      })
  
      return {
        amount,
        loading,
        clearLoading,
        error,
        rechargeHistory,
        historyLoading,
        amountRules,
        historyHeaders,
        isValidAmount,
        handleRecharge,
        clearPendingCharge,
        formatDate
      }
    }
  }
  </script>
  
  <style scoped>
  .v-card {
    border-radius: 12px;
  }
  
  .v-btn {
    border-radius: 8px;
  }
  </style>